<template>
  <div class="content">
    <a-row :gutter="8">
      <a-col :span="14">
        <div class="relative">
          <table id="printTable" border="0" center cellSpacing="0" cellPadding="1" width="100%" style="border-collapse: collapse; font-size: 10pt">
            <thead>
              <tr>
                <td colspan="12">
                  <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700">{{ orderInfo.dealer_name }}订单 </div>
                  <font style="position: absolute; right: 0; top: 0">
                    <span tdata="pageNO" format="#">#</span>
                    <span>/</span>
                    <span tdata="pageCount" format="#">##</span>
                  </font>
                </td>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td colspan="12"> 客户: {{ orderInfo.customer_name }}&nbsp;&nbsp;&nbsp;&nbsp; {{ orderInfo.warehouse_name }}&nbsp;&nbsp;&nbsp;&nbsp; 业务员: {{ orderInfo.salesman_name }}&nbsp;&nbsp;&nbsp;&nbsp; 业务员电话: {{ orderInfo.salesman_phone }}&nbsp;&nbsp;&nbsp;&nbsp; 配送司机: {{ orderInfo.driver_name }}&nbsp;&nbsp;&nbsp;&nbsp;结款方式：{{ getDescByValue('RECEIVE_TYPE_ENUM', orderInfo.payment_type) }} </td>
              </tr>
              <tr>
                <td colspan="12"> 单据编号：{{ orderInfo.order_no }}&nbsp;&nbsp;&nbsp;&nbsp; 订单类型：{{ getDescByValue('ORDER_STATRS_ENUM', orderInfo.order_type) }}&nbsp;&nbsp;&nbsp;&nbsp; 下单日期: {{ orderInfo.order_date }} </td>
              </tr>
              <tr>
                <td width="7%" style="border: 1pt solid #000">
                  <div align="center"><b>序号</b></div>
                </td>
                <td width="12%" style="border: 1pt solid #000">
                  <div align="center"><b>条码</b></div>
                </td>
                <td width="18%" style="border: 1pt solid #000">
                  <div align="center"><b>商品名称</b></div>
                </td>
                <td width="5%" style="border: 1pt solid #000">
                  <div align="center"><b>规格</b></div>
                </td>
                <td width="5%" style="border: 1pt solid #000">
                  <div align="center"><b>单位</b></div>
                </td>
                <td width="7%" style="border: 1pt solid #000">
                  <div align="center"><b>数量</b></div>
                </td>
                <td width="7%" style="border: 1pt solid #000">
                  <div align="center"><b>单价</b></div>
                </td>
                <td width="7%" style="border: 1pt solid #000">
                  <div align="center"><b>小计</b></div>
                </td>
                <td width="10%" style="border: 1pt solid #000">
                  <div align="center"><b>生产日期</b></div>
                </td>
                <td width="7%" style="border: 1pt solid #000">
                  <div align="center"><b>保质期</b></div>
                </td>
                <td width="5%" style="border: 1pt solid #000">
                  <div align="center"><b>属性</b></div>
                </td>
                <td width="10%" style="border: 1pt solid #000">
                  <div align="center"><b>备注</b></div>
                </td>
              </tr>
              <tr v-for="(goods, index) in goodsData" :key="goods.id" @click="selectGoods(goods)" :style="{ background: currentGoodsId.has(goods.id) ? '#e6f7ff' : '', cursor: 'pointer' }">
                <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.barcode }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.name }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.specification }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.unit }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.quantity }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.price }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ Number(goods.amount).toFixed(2) }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.production_date }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.shelf_life }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.attribute }}</td>
                <td style="border: 1pt solid #000; text-align: center">{{ goods.remark }}</td>
              </tr>
              <tr>
                <td style="border: 1pt solid #000; text-align: center; font-weight: 700">总计</td>
                <td style="border: 1pt solid #000"></td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000; text-align: center">{{ total_price }}</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
                <td style="border: 1pt solid #000">&nbsp;</td>
              </tr>
              <tr>
                <td colspan="12"> 地址：{{ orderInfo.store_address }}&nbsp;&nbsp;&nbsp;&nbsp; 电话：{{ orderInfo.store_phone }}&nbsp;&nbsp;&nbsp;&nbsp; 门店负责人：{{ orderInfo.responsible_person }}&nbsp;&nbsp;&nbsp;&nbsp; 制单：{{ orderInfo.maker }}&nbsp;&nbsp;&nbsp;&nbsp; </td>
              </tr>
              <tr>
                <td colspan="12">
                  <span style="font-weight: 700">备注：{{ orderInfo.remark }}</span>
                </td>
              </tr>
              <tr>
                <td colspan="12" style="font-weight: 500; font-size: 12px">声明：请店方不要接受业务/司机个人的欠条、收据等行为，如有发生纯属店方与业务/司机的个人责任，与我司无关，（交纳预收款请店方提前核实后再交纳）。我司对业务/司机个人所打欠条、收据等概不负责！</td>
              </tr>
            </tbody>
          </table>
        </div>
      </a-col>
      <a-col :span="10">
        <a-form ref="formRef" :model="orderInfo" :label-col="{ span: 8 }">
          <a-card title="订单信息" class="smart-margin-bottom10">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :span="12">
                <a-form-item label="结款方式" name="payment_type" required>
                  <a-select v-model:value="orderInfo.payment_type" style="width: 100%" placeholder="请选择结算方式" :dropdownMatchSelectWidth="false" :showSearch="true" :allowClear="true">
                    <a-select-option v-for="item in getValueDescList('RECEIVE_TYPE_ENUM')" :key="item.value" :value="item.value">
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
        <a-form ref="goodsFormRef" :model="orderInfo.goods" :label-col="{ span: 8 }">
          <a-card title="商品信息" class="smart-margin-bottom10">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :span="12">
                <a-form-item label="条码" name="barcode" required>
                  <a-input v-model:value="orderInfo.goods.barcode" placeholder="请输入条码"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="商品名称" name="name" required>
                  <a-input v-model:value="orderInfo.goods.name" placeholder="请输入商品名称"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="规格" name="specification" required>
                  <a-input v-model:value="orderInfo.goods.specification" placeholder="请输入规格"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="单位" name="unit" required>
                  <a-input v-model:value="orderInfo.goods.unit" placeholder="请输入单位"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="数量" name="quantity" required>
                  <a-input v-model:value="orderInfo.goods.quantity" placeholder="请输入数量"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="单价" name="price" required>
                  <a-input v-model:value="orderInfo.goods.price" placeholder="请输入单价"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="小计" name="amount" required>
                  <a-input v-model:value="orderInfo.goods.amount" placeholder="请输入小计"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="生产日期" name="production_date">
                  <a-input v-model:value="orderInfo.goods.production_date" placeholder="请输入生产日期"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="保质期" name="shelf_life">
                  <a-input v-model:value="orderInfo.goods.shelf_life" placeholder="请输入保质期"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="属性" name="attribute">
                  <a-input v-model:value="orderInfo.goods.attribute" placeholder="请输入属性"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="备注" name="remark">
                  <a-input v-model:value="orderInfo.goods.remark" placeholder="请输入备注"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :offset="8">
                <a-button @click="removeGoods" :disabled="currentGoodsId.size === 0">删除</a-button>
              </a-col>
              <a-col :offset="4">
                <a-button type="primary" @click="addGoods">{{ currentGoodsId.size === 0 ? '添加' : '修改' }}</a-button>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
      </a-col>
    </a-row>
    <a-row justify="center">
      <div class="smart-table-operate-block">
        <a-button type="primary" @click="onPrint">打印</a-button>
      </div>
    </a-row>
    <printModal :open="showErrorModal" @cancel="handleModalClose" />
  </div>
</template>
<script setup lang="ts">
import _ from 'lodash'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import printModal from '@/components/business/print-modal/index.vue'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import { useUserStore } from '@/store/modules/user-store'
import { salesApi } from '@/api/business/sale/sales-api'
import { useEnums } from '@/hooks/plugins/useEnums'
import { ORDER_STATRS_ENUM } from '@/constants/business/orders-const'
const { getUserInfo } = useUserStore()
const { query } = useRoute()
const { getDescByValue, getValueDescList } = useEnums()
const defaultOrderInfo = {
  // 经销商名称
  dealer_name: '',
  // 客户名称
  customer_name: '',
  // 出货仓库
  warehouse_name: '',
  // 业务员
  salesman_name: '',
  // 业务员电话
  salesman_phone: '',
  // 配送司机
  driver_name: '',
  // 单据编号
  order_no: '',
  // 订单类型
  order_type: '',
  // 结款方式
  payment_type: '',
  // 订单日期
  order_date: '',
  // 门店地址
  store_address: '',
  // 门店电话
  store_phone: '',
  // 负责人
  responsible_person: '',
  // 制单
  maker: getUserInfo.username,
  // 备注
  remark: '',
  goods: {
    // 商品名称
    name: '',
    // 条码(小)
    barcode: '',
    // 规格
    specification: '',
    // 单位
    unit: '',
    // 数量
    quantity: '',
    // 单价
    price: '',
    // 小计
    amount: '',
    // 生产日期
    production_date: '',
    // 保质期
    shelf_life: '',
    // 属性
    attribute: '',
    // 备注
    remark: ''
  }
}
const orderInfo = ref(_.cloneDeep(defaultOrderInfo))
const goodsData = ref<any[]>([])
const total_price = computed(() => {
  return _(goodsData.value)
    .map(({ amount }) => Number(amount))
    .sumBy()
    .toFixed(2)
})
const currentGoodsId = reactive<Set<string>>(new Set())

const formRef = ref()
const goodsFormRef = ref()

async function getOrderInfo() {
  try {
    const res = await salesApi.detail({ id: query.order })
    if (res.code === 200) {
      const { dealer, store, salesman, warehouse, order_type, delivery } = res.data
      let warehouse_name = ''

      if (order_type === ORDER_STATRS_ENUM.BARTER.value) {
        warehouse_name = `出库仓库: ${warehouse.name}(${warehouse.attribute_type_name})退回仓库: ${res.data.returnWarehouse.name}(${res.data.returnWarehouse.attribute_type_name})`
      } else if (order_type === ORDER_STATRS_ENUM.CASH.value) {
        warehouse_name = `出库仓库: ${warehouse.name}(${warehouse.attribute_type_name})`
      } else if (order_type === ORDER_STATRS_ENUM.ACCOUNT.value) {
        warehouse_name = `入库仓库: ${warehouse.name}(${warehouse.attribute_type_name})`
      }
      const order = {
        // 经销商名称
        dealer_name: dealer.name,
        // 客户名称
        customer_name: store.store_name,
        // 出货仓库
        warehouse_name,
        // 业务员(门店端下单没有业务员)
        salesman_name: salesman?.rename || '-',
        // 业务员电话
        salesman_phone: salesman?.phone || '-',
        // 配送司机
        driver_name: delivery.driver.name,
        // 单据编号
        order_no: res.data.no,
        // 订单类型
        order_type: res.data.order_type,
        // 结款方式
        payment_type: res.data.payment_type,
        // 订单日期
        order_date: res.data.create_time,
        // 门店地址
        store_address: store.address,
        // 门店电话
        store_phone: store.phone,
        // 负责人
        responsible_person: store.contacts,
        // 备注
        remark: res.data.remark
      }
      orderInfo.value = Object.assign({}, orderInfo.value, order)
      goodsData.value = res.data.detail.map((item) => {
        return {
          id: item.id,
          // 商品名称
          name: item.goods.goods_name,
          // 条码(小)
          barcode: item.spec.barcode,
          // 规格
          specification: item.spec.spec_name,
          // 单位
          unit: item.spec.unit_name,
          // 数量
          quantity: item.num,
          // 单价
          price: Number(item.real_price).toFixed(2),
          // 金额
          amount: item.total_price,
          // 生产日期
          production_date: dayjs(item.batch_info?.batch_time).format('YYYY-MM-DD') || '',
          // 保质期
          shelf_life: item.goods.shelf_life_day ? `${item.goods.shelf_life_day}天` : '',
          // 属性
          attribute: getDescByValue('GOODS_TYPE_ENUM', item.type),
          // 备注
          remark: item.remark
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}
onMounted(getOrderInfo)
function addGoods() {
  goodsFormRef.value.validate().then(() => {
    const index = goodsData.value.findIndex((item) => item.id === orderInfo.value.goods.id)
    if (index > -1) {
      goodsData.value.splice(index, 1, orderInfo.value.goods)
    } else {
      goodsData.value.push(Object.assign({ id: new Date().getTime().toString() }, orderInfo.value.goods))
    }
    orderInfo.value.goods = _.cloneDeep(defaultOrderInfo.goods)
    currentGoodsId.delete(orderInfo.value.goods.id)
  })
}
function removeGoods() {
  if (currentGoodsId.size === 0) return
  for (const key of currentGoodsId.values()) {
    const index = goodsData.value.findIndex((item) => Number(item.id) === Number(key))
    if (index > -1) {
      goodsData.value.splice(index, 1)
      orderInfo.value.goods = _.cloneDeep(defaultOrderInfo.goods)
    }
  }
  currentGoodsId.clear()
}
function selectGoods(goods: any) {
  if (currentGoodsId.has(goods.id)) {
    currentGoodsId.delete(goods.id)
    orderInfo.value.goods = _.cloneDeep(defaultOrderInfo.goods)
    return
  }
  orderInfo.value.goods = goods
  currentGoodsId.add(goods.id)
}
watch(
  () => [orderInfo.value.goods.price, orderInfo.value.goods.quantity],
  ([price, quantity]) => {
    if (price && quantity) {
      orderInfo.value.goods.amount = (Number(price) * Number(quantity)).toFixed(2)
    }
  }
)

const loading = ref(false)

const onPrint = () => {
  loading.value = true
  const LODOP = getLodop()
  if (!LODOP) {
    showErrorModal.value = true
    loading.value = false
    return
  }
  if (goodsData.value.length === 0) {
    message.error('请添加商品')
    loading.value = false
    return
  }
  formRef.value
    .validate()
    .then(() => {
      LODOP.PRINT_INITA(20, '0mm', '241mm', '93mm', '配送单')
      LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', '配送单')
      LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')
      LODOP.ADD_PRINT_TEXT(0, '5%', 196, 20, '县链云仓')
      LODOP.ADD_PRINT_TABLE(0, '5%', '90%', '100%', document.getElementById('printTable')?.outerHTML)
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 0)
      LODOP.NewPageA()
      LODOP.PREVIEW()
    })
    .finally(() => {
      loading.value = false
    })
}

const showErrorModal = ref(false)
const handleModalClose = () => {
  showErrorModal.value = false
}
</script>
<style scoped lang="less">
.content {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  padding: 20px;
}
</style>
